//
//  HomeViewController.m
//  iShop
//
//  Created by svp on 17/12/2011.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "HomeViewController.h"
#import "CustomCategoryViewController.h"
#import "HobbiesViewController.h"
#import "SearchViewController.h"
#import "UIImageEx.h"
#import "ResourceLoader.h"
#import "MapDirectionViewController.h"
#import "iShopAppDelegate.h"
#import "Utils.h"
#import "CoreDataUtils.h"
#import "LoginViewController.h"
#import "ChangePasswordViewController.h"
#import "ConstansDefine.h"
#import "LogoutRequest.h"

@interface HomeViewController(Private)

-(void) showFetchError:(NSError*) error;

@end


@implementation HomeViewController

@synthesize tableView = _tableView;
@synthesize fetchedResultsController = _fetchedResultsController;
@synthesize hobbiesButton = _hobbiesButton;

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/

/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

-(void) viewWillAppear:(BOOL)animated
{
	[super viewWillAppear:animated];
	self.navigationController.toolbarHidden = YES;
	UIBarButtonItem *backButton = [[UIBarButtonItem alloc] init];
	backButton.title = @"Back";
	self.navigationItem.backBarButtonItem = backButton;
	[backButton release];
	
	UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@"Account" style:UIBarButtonItemStylePlain target:self action:@selector(accountFunctionPress)];
	self.navigationItem.leftBarButtonItem = leftButton;
	[leftButton release];
	
	self.title = @"Clover Shop";
	//shopNameArray = [[NSMutableArray alloc] initWithArray:[NSArray arrayWithObjects:@"Phong Cách 9x", @"Venus", @"Lolita", @"Sea", @"Thời Trang Mỹ", @"Cicada", @"Coplay", @"My Style", @"Domino", @"Trẻ Trung", nil]];

	NSObject *ksession = [Utils getValueForRefKey:kSessionKey];
	if (!ksession || ksession == [NSNull null]) {
		_hobbiesButton.enabled = NO;
	}
	else {
		_hobbiesButton.enabled= YES;
	}

}

-(void) accountFunctionPress
{
	NSObject *ksession = [Utils getValueForRefKey:kSessionKey];
	if (!ksession || ksession == [NSNull null]) {
		LoginViewController *vc = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil];
		[self.navigationController presentModalViewController:vc animated:NO];
		[vc release];
	}
	else {
		UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"Select function" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Change Password",@"Log out",nil];
		[sheet showInView:self.view];
	}	
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
	if ([actionSheet.title isEqualToString:@"Select function"]) {
		if (buttonIndex != actionSheet.cancelButtonIndex) {
			if (buttonIndex == 0) {
				ChangePasswordViewController *vc = [[ChangePasswordViewController alloc] initWithNibName:@"ChangePasswordViewController" bundle:nil];
				[self.navigationController presentModalViewController:vc animated:NO];
				[vc release];
			}
			else {
				
				LogoutRequest *request = [[LogoutRequest alloc] init];
				[request makeRequest];
				LoginViewController *vc = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil];
				[self.navigationController presentModalViewController:vc animated:NO];
				[vc release];
			}

		}
	}
}

-(void) viewDidLoad
{
	[super viewDidLoad];
	if (![self fetchedResultsController]) {
		NSLog(@"1234567890-=");
	}
}

- (void)dealloc {
	NSLog(@"HomeViewController");
	[_tableView release];
    [super dealloc];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
    return [sectionInfo numberOfObjects];
}

- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
	
	Shop *shop = (Shop*)[self.fetchedResultsController objectAtIndexPath:indexPath];
	cell.imageView.image = [[[Utils getImageOf:@"shop" withName:shop.ShopImage] changeWhiteColorTransparent] scaleToSize:CGSizeMake(40, 40)];
	//((ShopCell*)cell).shopName.text = [shopNameArray objectAtIndex:indexPath.row];//shop.ShopName;
	((ShopCell*)cell).shopName.text = shop.ShopName;
	((ShopCell*)cell).shopAddress.text = shop.ShopAddress;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	ShopCell *cell = (ShopCell*)[tableView dequeueReusableCellWithIdentifier:@"ShopCell"];
	if (!cell) {
		ResourceLoader *rc = [[[ResourceLoader alloc] initWithNibNamed:@"ShopCell"] autorelease];
		cell = (ShopCell*)rc.resource;
		[cell.searchMap setImage:[[[UIImage imageNamed:@"search 6.jpg"] changeWhiteColorTransparent] scaleToSize:CGSizeMake(38, 38)] forState:UIControlStateNormal];

		cell.delegate = self;
	}
	[self configureCell:cell atIndexPath:indexPath];
	return cell;
}

-(void) viewMap:(ShopCell*)cell
{
	[self tableView: self.tableView accessoryButtonTappedForRowWithIndexPath:[self.tableView indexPathForCell:cell]];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	NSLog(@"didSelectRowAtIndexPath:%@",indexPath);
	Shop *shop = (Shop*)[self.fetchedResultsController objectAtIndexPath:indexPath];
	CustomCategoryViewController *custom = [[CustomCategoryViewController alloc] initWithNibName:@"CustomCategoryViewController" bundle: nil];
	custom.shop = shop;
	[self.navigationController pushViewController:custom animated:YES];
	[custom release];
}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
	Shop *shop = (Shop*)[self.fetchedResultsController objectAtIndexPath:indexPath];
	MapDirectionViewController *custom = [[MapDirectionViewController alloc] initWithNibName:@"MapDirectionViewController" bundle: nil];
	custom.shopAddress = [NSString stringWithFormat:@"%@,%@",shop.ShopLatitude , shop.ShopLongitude];
	[self.navigationController presentModalViewController:custom animated:YES];
	[custom release];
}

-(IBAction) openHobbies:(id) sender
{
	NSLog(@"openHobbies");	
	HobbiesViewController *custom = [[HobbiesViewController alloc] initWithNibName:@"HobbiesViewController" bundle: nil];
	UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:custom];
	[self.navigationController presentModalViewController:nav animated:NO];
	[custom release];
	[nav release];
}

-(IBAction) openSearchScreen:(id) sender
{
	NSLog(@"openSearchScreen");
	SearchViewController *custom = [[SearchViewController alloc] initWithNibName:@"SearchViewController" bundle: nil];
	UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:custom];
	[self.navigationController presentModalViewController:nav animated:NO];
	//[self.navigationController pushViewController:custom animated:YES];
	[custom release];
	[nav release];
}

#pragma mark -
#pragma mark Fetched results controller

- (NSFetchedResultsController *)fetchedResultsController {
	
	if (_fetchedResultsController) {
		return _fetchedResultsController;
	}
	NSManagedObjectContext *moc = [(iShopAppDelegate*)[[UIApplication sharedApplication] delegate] managedObjectContext];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Shop" inManagedObjectContext:moc];
    [fetchRequest setEntity:entity];
    
    [fetchRequest setFetchBatchSize:20];
    
    
    [fetchRequest setSortDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"ShopID" ascending:YES]]];
//	
//	if([_fetchAttrib objectAtIndex:EPredicate]!=[NSNull null]){
//		
//	}
	
	NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:moc sectionNameKeyPath:nil cacheName:nil];
    
	
	self.fetchedResultsController = aFetchedResultsController;
	self.fetchedResultsController.delegate = self;
	
	NSError *error = nil;
	if (![_fetchedResultsController performFetch:&error]) 		
		[self showFetchError:error];
	
    
	return _fetchedResultsController;
}

-(void) showFetchError:(NSError*) error
{
	
	NSLog(@"FetchError:%@",[error description]);
}
#pragma mark -
#pragma mark Fetched results controller delegate


- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
    [self.tableView beginUpdates];
}


- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo
           atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type {
	
    switch(type) {
        case NSFetchedResultsChangeInsert:
            [self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
            break;
            
        case NSFetchedResultsChangeDelete:
            [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
            break;
    }
}


- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
       atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
      newIndexPath:(NSIndexPath *)newIndexPath {
	
    
    UITableView *tableView = self.tableView;
	
    
    switch(type) {
            
        case NSFetchedResultsChangeInsert:
            [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
            break;
            
        case NSFetchedResultsChangeDelete:
            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
			break;
            
        case NSFetchedResultsChangeUpdate:
            [self configureCell:[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
            break;
            
        case NSFetchedResultsChangeMove:
            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
            [tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]withRowAnimation:UITableViewRowAnimationFade];
            break;
    }
}


- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
	
    [self.tableView endUpdates];
}
@end
